package com.talent.service.iot.mqtt.codec.encoder;

import com.talent.service.iot.mqtt.model.fix.TlMqttFixedHead;
import com.talent.service.iot.mqtt.model.request.TlMqttPublishReq;
import com.talent.service.iot.mqtt.model.variable.TlMqttPublishVariableHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @ClassName：TlConnackDecoder
 * @Author: hszhou
 * @Date: 2024/11/30 15:35
 * @Description: puback的编码
 */
@ChannelHandler.Sharable
@Component
public class TlMqttPublishEncoder extends MessageToByteEncoder<TlMqttPublishReq> {


    private static final  Logger logger = LoggerFactory.getLogger(TlMqttPublishEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, TlMqttPublishReq req, ByteBuf out) throws Exception {
        logger.debug("in【PUBLISH】encode");
        TlMqttFixedHead fixedHead = req.getFixedHead();
        TlMqttPublishVariableHead variableHead = req.getVariableHead();

        int type =  getFixedHeaderByte(fixedHead);
        MqttQoS qos = fixedHead.getQos();
        //消息类型
        out.writeByte(type);

        String topic = variableHead.getTopic();
        byte[] topicBytes = topic.getBytes();
        Object content = req.getPayload().getContent();
        byte[] bytes =content.toString().getBytes();
        // 2个字节的主题名称+主题字节的长度+载荷的长度 //如果消息的qos不是0  加上2个自己的消息长度
        int remindLength =Short.BYTES+topic.getBytes().length +bytes.length;
        if(qos!=MqttQoS.AT_MOST_ONCE){
            remindLength=remindLength+Short.BYTES;
        }
        //剩余长度
        out.writeByte(remindLength);
        out.writeShort(topicBytes.length);
        out.writeBytes(topicBytes);
        Integer messageId = variableHead.getMessageId();
        if(qos!=MqttQoS.AT_MOST_ONCE){
            out.writeShort(messageId);
        }
        out.writeBytes(bytes);
    }




    private  int getFixedHeaderByte(TlMqttFixedHead header) {
        int ret = 0;
        ret |= header.getMessageType().value() << 4;
        if (header.getDup()) {
            ret |= 0x08;
        }
        ret |= header.getQos().value() << 1;
        if (header.getRetain()) {
            ret |= 0x01;
        }
        return ret;
    }

}
